package com.copa.l200;

/**
 * @author copa
 * @createDate 2022-05-23 09:42
 * @function DFS
 */
public class Test1 {

    public int numIslands(char[][] grid) {
        // 由于题目给出grid的x，y轴肯定>=1，所以不用判断非空
        // x的长度
        int row = grid.length;
        // y的长度
        int col = grid[0].length;
        // 新大陆数
        int result = 0;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (grid[i][j] == '1') {
                    // 如果发现是陆地，先增加再dfs
                    result++;
                    dfs(grid, i, j, row, col);
                }
            }
        }
        return result;
    }

    private void dfs(char[][] grid, int x, int y, int row, int col) {
        if (x < 0 || y < 0 || x >= row || y >= col || grid[x][y] == '0') {
            // 查询范围越界或者是水地的话直接返回
            return;
        }
        // 把该坐标的陆地同化成水
        grid[x][y] = '0';
        // 往左遍历
        dfs(grid, x - 1, y, row, col);
        // 往右遍历
        dfs(grid, x + 1, y, row, col);
        // 往上遍历
        dfs(grid, x, y - 1, row, col);
        // 往下遍历
        dfs(grid, x, y + 1, row, col);
    }

    public static void main(String[] args) {
        char[][] grid = new char[][]{
                {'1','1','0','0','0'},
                {'1','1','0','0','0'},
                {'0','0','1','0','0'},
                {'0','0','0','1','1'}
        };
        System.out.println(new Test1().numIslands(grid));
    }
}
